/** @module request */
const api = "http://test.app.enjoybuy.vip:81"

/**
 * 接口请求
 * @property { Object } config 配置
 * @property { String } config.url 请求地址
 * @property { String } [ config.method = GET ] 请求类型
 * @property { Object } config.data 请求参数
 * @property { Object } [ config.header = { 'content-type': 'application/x-www-form-urlencoded' }] 请求头
 * @property { Boolean } [ config.isLoad = false ] 是否需要加载效果
 * @example
 * request({url: '/api/login/login', method: 'GET', data: {}).then(res=>{}).catch(error=>{})
 */

function request(config) {
  const url = config.url
  const method = config.method || 'GET'
  const data = config.data || {}
  const header = config.header || {
    'content-type': 'application/x-www-form-urlencoded'
  }
  if (wx.getStorageSync('token')) {
    header['AGENTTOKEN'] = wx.getStorageSync('token')
  }
  const isLoad = config.isLoad || false
  if (isLoad) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    if (url === '' && !url) {
      reject(new Error('request url can not be empty'));
    }
    wx.request({
      url: api + url,
      method,
      data,
      header,
      timeout: 6000,
      success: res => {
        if (isLoad) {
          wx.hideLoading()
        }
        const data = res.data
        if (data.code === 200) {
          resolve(data)
        } else if (data.code === 1001 || data.code === 1002 || data.code === 1003) {

        } else {
          wx.showToast({
            title: data.message || '服务异常，请稍后再试',
            icon: 'waiting',
            mask: true
          })
        }
      },
      fail: error => {
        if (isLoad) {
          wx.hideLoading()
        }
        if (error.message.includes('timeout')) {
          wx.showToast({
            title: '请求超时',
            icon: 'waiting',
            mask: true
          })
        } else {
          wx.showToast({
            title: error.message || '请求错误',
            icon: 'waiting',
            mask: true
          })
        }
        reject(error)
      }
    })
  })
}
module.exports = {
  request: request
}
